package com.papper.common.service.base;

import com.papper.common.bean.base.BaseConstRegion;
import com.papper.common.cache.CacheConstants;
import com.papper.common.cache.redis.CacheClosureNullDefault;
import com.papper.common.mapper.base.BaseConstRegionMapper;
import com.papper.common.service.ServiceImpl;
import com.papper.common.utils.tool.StringTool;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @Author:LaJiao
 * @Date:2022-03-29 10:06:49
 * @Description:地区列表
 */
@Service("baseConstRegionService")
public class BaseConstRegionService extends ServiceImpl<BaseConstRegionMapper, BaseConstRegion> {

    @Override
    protected void clearCaches(BaseConstRegion entity) {
        super.clearCaches(entity);
        cache.delete(CacheConstants.Keys(getModel(), entity.getRegionCode()));
    }

    public BaseConstRegion findByCode(final String regionCode) {
        if (StringTool.isEmpty(regionCode)) {
            return null;
        }
        return cache.getAndSet(new CacheClosureNullDefault<BaseConstRegion>() {
            @Override
            public String getKey() {
                return CacheConstants.Keys(getModel(), regionCode);
            }

            @Override
            public BaseConstRegion getValue() {
                Example          example  = new Example(BaseConstRegion.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("regionCode", regionCode);
                return findOne(example);
            }

            @Override
            public Class<BaseConstRegion> getTypeReference() {
                return BaseConstRegion.class;
            }
        });
    }

    public List<BaseConstRegion> findByParent(String parentId) {
        Example          example  = new Example(BaseConstRegion.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("parentId", parentId);
        return find(example);
    }

    public List<BaseConstRegion> findByTypeWithName(String regionType, String regionName) {
        Example          example  = new Example(BaseConstRegion.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("regionType", regionType);
        criteria.andEqualTo("regionName", regionName);
        return find(example);
    }
}
